﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Lists;
using Vouchers;
using GeneralLibs;
using System.Data.SqlClient;
using BasicForms;
using BarcodeLib;

using System.Diagnostics;
using System.Drawing.Printing;
using System.Management;

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Diagnostics;
using System.Drawing.Printing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

using System.Threading;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using Microsoft.Win32;

namespace BarCode
{
    public partial class FrmBarCode : BasicForms.FrmBase
    {
        [DllImport("Winspool.drv")]
        private static extern bool SetDefaultPrinter(string printerName);

        const int BARCODE_WIDTH = 190;
        const int BARCODE_HEIGHT = 49;
        public double cPrinterWidth, cPrinterHeight;
        int ColsPerPage, RowsPerPage;

        public void GetValue(ref int SoCot, ref int SoDong, ref double Widths, ref double Hegihts)
        {
            SoCot = ColsPerPage;
            SoDong = RowsPerPage;
            Widths = cPrinterWidth;
            Hegihts = cPrinterHeight;
        }
        public FrmBarCode()
        {
            InitializeComponent();
        }
        private void FrmMain_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;

            numSoLuongIn.Properties.ReadOnly = true;

            #region cmbDoiTuong
            cmbDoiTuong.DataSource = DanhMucDoiTuongNghiepVu.GetDanhMucNhaCungCap().DataView;
            cmbDoiTuong.DisplayColumn = "Ten";
            cmbDoiTuong.ValueColumn = "ID";
            cmbDoiTuong.AddVisibleColumn("Ma", "Mã");
            cmbDoiTuong.AddVisibleColumn("Ten", "Tên");
            #endregion

            #region cmbNhomHang
            cmbNhomHang.DataSource = DanhMucNhomVatTuHangHoa.GetAll().DataView;
            cmbNhomHang.DisplayColumn = "Ten";
            cmbNhomHang.ValueColumn = "ID";
            cmbNhomHang.AddVisibleColumn("Ma", "Mã");
            cmbNhomHang.AddVisibleColumn("Ten", "Tên");
            #endregion

            CbPaperStyle.SelectedIndex = 1;
            CbDonVi.SelectedIndex = 0;
            for (int i = 0; i < RowsPerPage * ColsPerPage; i++)
            {
                CbStartAt.Items.Add(i);
            }
            CbStartAt.SelectedIndex = 0;

            numSoLuongIn.EditValue = 1;
            //Cần bao nhiêu cột thì điền vào đây,rồi dưới add từng đó trường
            DgrInHang.ColumnCount = 7;

            if (!RdoTheoPhieuNhap.Checked && !RdoToanBoKhoHang.Checked)
            {
                txtFindMa.Enabled = false;
                TxtFindName.Enabled = false;
            }

            DgrHangHoa.AllowUserToAddRows = false;
            DgrHangHoa.ReadOnly = true;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            switch (keyData)
            {
                case Keys.Escape:
                    this.Close();
                    break;
                case Keys.Control | Keys.Q:
                    this.Close();
                    return true;
                    break;
                case Keys.Enter:
                    ChooseForPrint();
                    return true;
                    break;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        public void ChooseForPrint()
        {
            try
            {
                //DgrInHang.ColumnCount = 5;
                if (!(cmbDoiTuong.EditValue is Guid) || (Guid)cmbDoiTuong.EditValue == Guid.Empty)
                {
                    if (DanhMucStore.Instance.CurrentStore().Ten.ToUpper().Contains("IBOOK") ||
                        DanhMucStore.Instance.CurrentStore().Ten.ToUpper().Contains("PHSPHUTHO"))
                    {
                        string a = "Không làm gì cả";
                    }
                    else
                    {
                        MessageBox.Show("Bạn chưa chọn nhà cung cấp mặt hàng");
                        cmbDoiTuong.Focus();
                        return;
                    }
                }

                if (DgrHangHoa["Ma", DgrHangHoa.SelectedRows[0].Index].Value == null)
                {
                    MessageBox.Show("Hàng bạn chọn không có mã");
                    return;
                }

                int count = DgrHangHoa.SelectedRows.Count;

                string maNCC = "";

                if (cmbDoiTuong.EditValue != null && (Guid)cmbDoiTuong.EditValue != Guid.Empty)
                {
                    DoiTuongNghiepVu dtnv = DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)cmbDoiTuong.EditValue);
                    if (dtnv != null)
                        maNCC = dtnv.Ma;
                }

                //1 số nơi không thích vậy nên 
                if (DanhMucStore.Instance.CurrentStore().Ten.ToUpper().Contains("IBOOK"))
                    maNCC = "IBOOK";
                else if (DanhMucStore.Instance.CurrentStore().Ten.ToUpper().Contains("PHSPHUTHO"))
                    maNCC = "";

                if (RdoTheoPhieuNhap.Checked)
                {
                    Store store = DanhMucStore.Instance.GetByStoreID(Config.StoreID);
                    if (store.Ten.ToUpper().Contains("VIETBOOK"))
                    {
                        for (int i = count - 1; i >= 0; i--)
                        {
                            //convert decimal -> int de hien cho chuan
                            int giaBia = Convert.ToInt32(DgrHangHoa["GiaBia", DgrHangHoa.SelectedRows[i].Index].Value);
                            int soLuong = Convert.ToInt32(DgrHangHoa["SoLuong", DgrHangHoa.SelectedRows[i].Index].Value);
                            DgrInHang.Rows.Add(DgrHangHoa["Ma", DgrHangHoa.SelectedRows[i].Index].Value, DgrHangHoa["Ten", DgrHangHoa.SelectedRows[i].Index].Value, giaBia, soLuong,
                                                      maNCC, DgrHangHoa["TenKho", DgrHangHoa.SelectedRows[i].Index].Value, DgrHangHoa["TenNhom", DgrHangHoa.SelectedRows[i].Index].Value);
                        }
                    }
                    else
                    {
                        for (int i = count - 1; i >= 0; i--)
                        {
                            //convert decimal -> int de hien cho chuan
                            int giaBia = Convert.ToInt32(DgrHangHoa["GiaBia", DgrHangHoa.SelectedRows[i].Index].Value);
                            int soLuong = Convert.ToInt32(DgrHangHoa["SoLuong", DgrHangHoa.SelectedRows[i].Index].Value);
                            DgrInHang.Rows.Add(DgrHangHoa["Ma", DgrHangHoa.SelectedRows[i].Index].Value, DgrHangHoa["Ten", DgrHangHoa.SelectedRows[i].Index].Value, giaBia, soLuong,//DgrHangHoa["GiaBia", DgrHangHoa.SelectedRows[i].Index].Value, DgrHangHoa["SoLuong", DgrHangHoa.SelectedRows[i].Index].Value,
                                                      maNCC);
                        }
                    }
                }
                else
                {
                    for (int i = count - 1; i >= 0; i--)
                    {
                        int giaBia = Convert.ToInt32(DgrHangHoa["GiaBia", DgrHangHoa.SelectedRows[i].Index].Value);
                        int soLuong = Convert.ToInt32(numSoLuongIn.EditValue);
                        DgrInHang.Rows.Add(DgrHangHoa["Ma", DgrHangHoa.SelectedRows[i].Index].Value, DgrHangHoa["Ten", DgrHangHoa.SelectedRows[i].Index].Value, giaBia, soLuong,//DgrHangHoa["GiaBia", DgrHangHoa.SelectedRows[i].Index].Value, numSoLuongIn.Value,
                                        maNCC);
                    }
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void TxtBarCode_TextChanged(object sender, EventArgs e)
        {
        }

        private void DgrHangHoa_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                TxtBarCode.Text = DgrHangHoa["Ma", DgrHangHoa.CurrentRow.Index].Value.ToString();
                TxtBookName.Text = DgrHangHoa["Ten", DgrHangHoa.CurrentRow.Index].Value.ToString();
                if (TxtBarCode.Text != "") TxtTopText.Text = DanhMucVatTuHangHoa.GetByMa(TxtBarCode.Text.ToString()).TenNganGon;
                TxtBottomText.Text = string.Format("{0:0,0}", Decimal.Parse((DgrHangHoa["GiaBia", DgrHangHoa.CurrentRow.Index].Value.ToString())));
                //LbBottom.Text = "Giá: " + string.Format("{0:0,0}", Decimal.Parse((DgrHangHoa["GiaBia", DgrHangHoa.CurrentRow.Index].Value.ToString()))); 
                //if(DgrHangHoa["Ten", DgrHangHoa.CurrentRow.Index].Value.ToString().Length>50)
                //{
                //    LbTop.Text = DgrHangHoa["Ten", DgrHangHoa.CurrentRow.Index].Value.ToString().Substring(0, 50);  
                //}
                if (RdoToanBoKhoHang.Checked == true)
                {
                    numSoLuongIn.EditValue = 1;
                }
                else
                {
                    numSoLuongIn.EditValue = (decimal)DgrHangHoa[3, DgrHangHoa.CurrentRow.Index].Value;
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void RdoToanBoKhoHang_CheckedChanged(object sender, EventArgs e)
        {
            if (RdoToanBoKhoHang.Checked)
            {
                DanhMucVatTuHangHoa.Instance.DataView.Table.DefaultView.Sort = "Ten";
                DgrHangHoa.DataSource = Lists.DanhMucVatTuHangHoa.GetDanhMucHangHoaDangSuDung().DataView;
                TxtFindName.Focus();
                DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bán lẻ";
                DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                for (int c = 0; c < DgrHangHoa.ColumnCount; c++)
                {
                    if ((DgrHangHoa.Columns[c].Name == "Ma") || (DgrHangHoa.Columns[c].Name == "Ten") || (DgrHangHoa.Columns[c].Name == "GiaBia"))
                    {
                        DgrHangHoa.Columns[c].Visible = true;
                    }
                    else
                    {
                        DgrHangHoa.Columns[c].Visible = false;
                    }
                }

                txtFindMa.Enabled = true;
                TxtFindName.Enabled = true;
                cmbDoiTuong.Enabled = true;
                dtNgayHoaDon.Enabled = false;
                cmbPhieuNhap.Enabled = false;
            }
            else
            {
                txtFindMa.Enabled = false;
                TxtFindName.Enabled = false;
                cmbDoiTuong.Enabled = false;
                dtNgayHoaDon.Enabled = true;
                cmbPhieuNhap.Enabled = true;
            }
        }

        private void RdoTheoPhieuNhap_CheckedChanged(object sender, EventArgs e)
        {
            if (RdoTheoPhieuNhap.Checked)
                SearhTheoHoaDon();

            FrmProgressBar.StartShowProgress();
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                txtFindMa.Text = "";
                TxtFindName.Text = "";

                if (cmbPhieuNhap.EditValue != null)
                {
                    // Hiện hàng phiếu nhập
                    cmd.CommandText = string.Format(
                               "SELECT B.Ma, B.Ten, B.GiaBia, F.Ma TenNhom, A.Value1 AS SoLuong, D.Ten 'TenNCC', E.Ma TenKho \n" +
                               "FROM KhoanMucChungTu A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoa1ID = B.ID \n" +
                               "    INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                               "    INNER JOIN DoiTuongNghiepVu D ON D.ID = C.DoiTuongNghiepVu1ID \n" +
                               "    INNER JOIN Kho E ON E.ID = C.Kho1ID \n" +
                               "    INNER JOIN NhomVatTuHangHoa F ON F.ID = B.NhomVatTuHangHoaID \n" +
                               "WHERE A.ChungTuID = '{2}' \n" +
                               "ORDER BY A.ThuTuKhoanMucTrongChungTu",
                               txtFindMa.Text, TxtFindName.Text, cmbPhieuNhap.EditValue
                               );

                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    DgrHangHoa.DataSource = ds.Tables[0].DefaultView;
                    DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bán lẻ";
                    DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                    DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                    DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                    DgrHangHoa.Columns["SoLuong"].HeaderText = "Số lượng";
                    DgrHangHoa.Columns["SoLuong"].DefaultCellStyle.Format = "0";
                    DgrHangHoa.Columns["TenNCC"].HeaderText = "Tên nhà cung cấp";
                    DgrHangHoa.Columns["TenNCC"].Width = 250;

                    DgrHangHoa.Columns["TenKho"].HeaderText = "Tên kho nhập";
                    DgrHangHoa.Columns["TenNhom"].HeaderText = "Tên kho nhập";

                    DgrHangHoa.Columns["TenKho"].Width = 250;
                    DgrHangHoa.Columns["TenNhom"].Width = 250;

                    cmd.CommandText = string.Format("SELECT DoiTuongNghiepVu1ID " +
                                                    "FROM ChungTu " +
                                                    "WHERE ChungTuID = '{0}'",
                                                    cmbPhieuNhap.EditValue);
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.Read())
                    {
                        cmbDoiTuong.EditValue = (Guid)dr["DoiTuongNghiepVu1ID"];
                    }
                    dr.Close();
                }
                DgrHangHoa.DataSource = null;
            }
            catch (Exception ex)
            {
                //BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
            }
            FrmProgressBar.FinishShowProgress();

            txtFindMa.Enabled = true;
            TxtFindName.Enabled = true;

        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            if (RdoTheoPhieuNhap.Checked)
                SearhTheoHoaDon();
        }

        private void SearhTheoHoaDon()
        {
            FrmProgressBar.StartShowProgress();
            try
            {
                DieuKienTimKiemChungTu dkTimKiem = new DieuKienTimKiemChungTu();
                DateTime today = dtNgayHoaDon.Value;
                dkTimKiem.TuNgay = new NullableDate(new DateTime(today.Year, today.Month, today.Day, 0, 0, 0));
                dkTimKiem.DenNgay = new NullableDate(new DateTime(today.Year, today.Month, today.Day, 23, 59, 59));

                //Nếu là PHS Phú Thọ thì hiện cả phiếu kiểm kê lên để in
                if (DanhMucStore.Instance.CurrentStore().Ten.ToUpper().Contains("PHSPHUTHO"))
                {
                    dkTimKiem.ListLoaiChungTu = "PhieuNhapKho, PhieuKiemKe";
                }
                else
                {
                    dkTimKiem.LoaiChungTu = DanhMucLoaiChungTu.Instance.GetByMa("PhieuNhapKho");
                }

                DanhSachChungTu dsHoaDonMua = new DanhSachChungTu();
                dsHoaDonMua.LoadFromDB(dkTimKiem.BuildSqlStatement(1000, 1));

                cmbPhieuNhap.DataSource = dsHoaDonMua.DataTable.DefaultView;
                cmbPhieuNhap.PopupWidth = 260;
                cmbPhieuNhap.PopupHeight = 200;
                cmbPhieuNhap.DisplayColumn = "So";
                cmbPhieuNhap.ValueColumn = "ChungTuID";
                cmbPhieuNhap.AddVisibleColumn("So", "Số phiếu", 130, 1);
                cmbPhieuNhap.AddVisibleColumn("SoChungTuGoc", "Số hóa đơn", 130, 2);
            }
            catch (SqlException sqlEx)
            {
                throw new CustomException(CustomException.GetSqlExceptionMessage(sqlEx));
            }
            catch (Exception ex)
            {
                if (ex is CustomException) throw ex;
                else
                {
                    throw new Exception(ex.Message);
                }
            }
            FrmProgressBar.FinishShowProgress();
        }

        private void CbPaperStyle_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (CbPaperStyle.SelectedIndex)
            {
                case 0:
                    {
                        cPrinterWidth = 106 * 56.7; //' 106 mm (x 56.7 twip)
                        cPrinterHeight = (73 * 56.7); //'4479 '79 mm
                        break;
                    }
                case 1:
                    {
                        cPrinterWidth = 6067;//' 107 mm (x 56.7 twip)
                        cPrinterHeight = 5670; //'100 mm
                        break;
                    }
                case 2:
                    {
                        cPrinterWidth = 5953; //' 105 mm (x 56.7 twip)
                        cPrinterHeight = 8788; //'155 mm
                        break;
                    }
                case 3:
                    {
                        cPrinterWidth = 11907;//' = 210 mm
                        cPrinterHeight = 16840;// '297 mm
                        break;
                    }
            }
            //CbX.SelectedIndex = Convert.ToInt32(cPrinterWidth / MyBarCode.Width - 1);  
            CbX.SelectedIndex = Convert.ToInt32((int)cPrinterWidth / (int)1815) - 1;
            //CbY.SelectedIndex = Convert.ToInt32(cPrinterHeight / (LbBottom.Top + LbBottom.Height - LbTop.Top) - 1);
            CbY.SelectedIndex = Convert.ToInt32((int)(cPrinterHeight) / (int)(1155)) - 1;
            ColsPerPage = CbX.SelectedIndex + 1;
            RowsPerPage = CbY.SelectedIndex + 1;
        }

        private void CbY_SelectedIndexChanged(object sender, EventArgs e)
        {
            RowsPerPage = CbY.SelectedIndex + 1;
        }

        private void CbX_SelectedIndexChanged(object sender, EventArgs e)
        {
            ColsPerPage = CbX.SelectedIndex + 1;
        }

        private void DgrInHang_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (DgrInHang.CurrentRow.Index != DgrInHang.RowCount - 1)
            {
                try
                {
                    TxtBarCode.Text = DgrInHang[0, DgrInHang.CurrentRow.Index].Value.ToString();
                    TxtBookName.Text = DgrInHang[1, DgrInHang.CurrentRow.Index].Value.ToString();
                    if (TxtBarCode.Text != "") TxtTopText.Text = DanhMucVatTuHangHoa.GetByMa(TxtBarCode.Text.ToString()).TenNganGon;
                    TxtBottomText.Text = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, DgrInHang.CurrentRow.Index].Value.ToString())));
                    //LbBottom.Text = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, DgrInHang.CurrentRow.Index].Value.ToString())));
                    //LbTop.Text = DgrInHang[1, DgrInHang.CurrentRow.Index].Value.ToString();
                    if (numSoLuongIn.Text == "")
                    {
                        numSoLuongIn.EditValue = 1;
                    }
                    else
                    {
                        numSoLuongIn.EditValue = Convert.ToInt32(DgrInHang[3, DgrInHang.CurrentRow.Index].Value);
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }

        private void numSoLuongIn_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void BtExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cmbPhieuNhap_EditValueChanged(object sender, EventArgs e)
        {
            FrmProgressBar.StartShowProgress();
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();

                txtFindMa.Text = "";
                TxtFindName.Text = "";

                if (cmbPhieuNhap.EditValue is Guid)
                {
                    try
                    {
                        if (cmbPhieuNhap.Text.Contains("PKK"))
                        {
                            //Hiện hàng Phiếu kiểm kê
                            cmd.CommandText = string.Format(
                                        "SELECT B.Ma, B.Ten, B.GiaBia, A.Value1 AS SoLuong, '' TenNCC \n " +
                                        "FROM KhoanMucChungTu A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoa1ID = B.ID  \n " +
                                        "WHERE A.ChungTuID = '{0}'  \n " +
                                        "ORDER BY A.ThuTuKhoanMucTrongChungTu \n ",
                                       cmbPhieuNhap.EditValue);
                        }
                        else
                        {
                            // Hiện hàng phiếu nhập
                            cmd.CommandText = string.Format(
                                        "SELECT B.Ma, B.Ten, B.GiaBia, F.Ma TenNhom, A.Value1 AS SoLuong, D.Ten 'TenNCC', E.Ma TenKho \n" +
                                       "FROM KhoanMucChungTu A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoa1ID = B.ID \n" +
                                       "    INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                                       "    INNER JOIN DoiTuongNghiepVu D ON D.ID = C.DoiTuongNghiepVu1ID \n" +
                                       "    INNER JOIN Kho E ON E.ID = C.Kho1ID \n" +
                                       "    INNER JOIN NhomVatTuHangHoa F ON F.ID = B.NhomVatTuHangHoaID \n" +
                                       "WHERE A.ChungTuID = '{2}' \n" +
                                       "ORDER BY A.ThuTuKhoanMucTrongChungTu",
                                       txtFindMa.Text, TxtFindName.Text, cmbPhieuNhap.EditValue
                                       );
                        }

                        SqlDataAdapter da = new SqlDataAdapter(cmd);
                        DataSet ds = new DataSet();
                        da = new SqlDataAdapter(cmd);
                        da.Fill(ds);

                        DgrHangHoa.DataSource = ds.Tables[0].DefaultView;
                        DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bán lẻ";
                        DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                        DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                        DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                        DgrHangHoa.Columns["SoLuong"].HeaderText = "Số lượng";
                        DgrHangHoa.Columns["SoLuong"].DefaultCellStyle.Format = "0";
                        DgrHangHoa.Columns["TenNCC"].HeaderText = "Tên nhà cung cấp";

                        DgrHangHoa.Columns["TenKho"].HeaderText = "Tên kho nhập";
                        DgrHangHoa.Columns["TenNhom"].HeaderText = "Tên kho nhập";

                        DgrHangHoa.Columns["TenKho"].Width = 250;
                        DgrHangHoa.Columns["TenNhom"].Width = 250;

                        DgrHangHoa.Columns["GiaBia"].Width = 80;
                        DgrHangHoa.Columns["Ten"].Width = 200;
                        DgrHangHoa.Columns["SoLuong"].Width = 60;
                        DgrHangHoa.Columns["TenNCC"].Width = 250;

                        try
                        {
                            cmd.CommandText = string.Format("SELECT DoiTuongNghiepVu1ID " +
                                                       "FROM ChungTu " +
                                                       "WHERE ChungTuID = '{0}'",
                                                       cmbPhieuNhap.EditValue);
                            SqlDataReader dr = cmd.ExecuteReader();
                            if (dr.Read())
                            {
                                cmbDoiTuong.EditValue = (Guid)dr["DoiTuongNghiepVu1ID"];
                            }
                            dr.Close();
                        }
                        catch (Exception ex)
                        {
                        }

                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
            }
            FrmProgressBar.FinishShowProgress();
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        private void TxtFindName_TextChanged(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();

                if (RdoTheoPhieuNhap.Checked)
                {
                    cmd.CommandText = string.Format(
                          "SELECT B.Ma, B.Ten, B.GiaBia, F.Ma TenNhom, A.Value1 AS SoLuong, D.Ten 'TenNCC', E.Ma TenKho \n" +
                           "FROM KhoanMucChungTu A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoa1ID = B.ID \n" +
                           "    INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                           "    INNER JOIN DoiTuongNghiepVu D ON D.ID = C.DoiTuongNghiepVu1ID \n" +
                           "    INNER JOIN Kho E ON E.ID = C.Kho1ID \n" +
                           "    INNER JOIN NhomVatTuHangHoa F ON F.ID = B.NhomVatTuHangHoaID \n" +
                           "WHERE B.Ma like N'%{0}%' AND B.Ten like N'%{1}%' AND (B.TrangThai = 1 OR B.TrangThai IS NULL) AND A.ChungTuID IN \n" +
                           "(  \n" +
                           "    SELECT ChungTuID \n" +
                           "    FROM ChungTu \n" +
                           "    WHERE ChungTuGocID = '{2}' \n" +
                           ") \n" +
                           "ORDER BY A.ThuTuKhoanMucTrongChungTu",
                           txtFindMa.Text, TxtFindName.Text, cmbPhieuNhap.EditValue
                           );
                }
                else
                {
                    cmd.CommandText = string.Format(
                                "SELECT Ma, Ten, GiaBia                     \n" +
                                "FROM VatTuHangHoa                          \n" +
                                "WHERE Ma like N'%{0}%' AND Ten like N'%{1}%' AND (TrangThai = 1 OR TrangThai IS NULL)  \n",
                                txtFindMa.Text, TxtFindName.Text
                                );
                }
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();

                da.Fill(ds);
                DgrHangHoa.DataSource = ds.Tables[0].DefaultView;
                DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bán lẻ";
                DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                if (RdoTheoPhieuNhap.Checked)
                {
                    try
                    {
                        DgrHangHoa.Columns["TenNCC"].HeaderText = "Tên nhà cung cấp";
                        DgrHangHoa.Columns["TenNCC"].Width = 250;

                        DgrHangHoa.Columns["TenKho"].HeaderText = "Tên kho nhập";
                        DgrHangHoa.Columns["TenNhom"].HeaderText = "Tên kho nhập";

                        DgrHangHoa.Columns["TenKho"].Width = 250;
                        DgrHangHoa.Columns["TenNhom"].Width = 250;
                    }
                    catch (Exception)
                    {
                    }
                }
                DgrHangHoa.Columns["GiaBia"].Width = 80;
                DgrHangHoa.Columns["Ten"].Width = 200;
                //DgrHangHoa.Columns["SoLuong"].Width = 60;

            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
            }
        }

        private void txtFindMa_TextChanged(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();

                if (RdoTheoPhieuNhap.Checked)
                {
                    cmd.CommandText = string.Format(
                         "SELECT B.Ma, B.Ten, B.GiaBia, F.Ma TenNhom, A.Value1 AS SoLuong, D.Ten 'TenNCC', E.Ma TenKho \n" +
                           "FROM KhoanMucChungTu A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoa1ID = B.ID \n" +
                           "    INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                           "    INNER JOIN DoiTuongNghiepVu D ON D.ID = C.DoiTuongNghiepVu1ID \n" +
                           "    INNER JOIN Kho E ON E.ID = C.Kho1ID \n" +
                           "    INNER JOIN NhomVatTuHangHoa F ON F.ID = B.NhomVatTuHangHoaID \n" +
                           "WHERE B.Ma like N'%{0}%' AND B.Ten like N'%{1}%' AND (B.TrangThai = 1 OR B.TrangThai IS NULL) AND A.ChungTuID IN \n" +
                           "(  \n" +
                           "    SELECT ChungTuID \n" +
                           "    FROM ChungTu \n" +
                           "    WHERE ChungTuGocID = '{2}' \n" +
                           ") \n" +
                           "    ORDER BY A.ThuTuKhoanMucTrongChungTu",
                           txtFindMa.Text, TxtFindName.Text, cmbPhieuNhap.EditValue
                           );
                }
                else
                {
                    cmd.CommandText = string.Format(
                                "SELECT Ma, Ten, GiaBia                     \n" +
                                "FROM VatTuHangHoa                          \n" +
                                "WHERE Ma like N'%{0}%' AND Ten like N'%{1}%' AND (TrangThai = 1 OR TrangThai IS NULL)  \n",
                                txtFindMa.Text, TxtFindName.Text
                                );
                }
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();

                da.Fill(ds);
                DgrHangHoa.DataSource = ds.Tables[0].DefaultView;
                DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bán lẻ";
                DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                if (RdoTheoPhieuNhap.Checked)
                {
                    try
                    {
                        DgrHangHoa.Columns["TenNCC"].HeaderText = "Tên nhà cung cấp";
                        DgrHangHoa.Columns["TenNCC"].Width = 250;

                        DgrHangHoa.Columns["TenKho"].HeaderText = "Tên kho nhập";
                        DgrHangHoa.Columns["TenNhom"].HeaderText = "Tên kho nhập";

                        DgrHangHoa.Columns["TenKho"].Width = 250;
                        DgrHangHoa.Columns["TenNhom"].Width = 250;
                    }
                    catch (Exception)
                    {
                    }
                }
                DgrHangHoa.Columns["GiaBia"].Width = 80;
                DgrHangHoa.Columns["Ten"].Width = 200;
                //DgrHangHoa.Columns["SoLuong"].Width = 60;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
            }
        }

        private void DgrHangHoa_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                //DgrInHang.ColumnCount = 5;
                if (!(cmbDoiTuong.EditValue is Guid) || (Guid)cmbDoiTuong.EditValue == Guid.Empty)
                {
                    if (DanhMucStore.Instance.CurrentStore().Ten.ToUpper().Contains("IBOOK") ||
                        DanhMucStore.Instance.CurrentStore().Ten.ToUpper().Contains("PHSPHUTHO"))
                    {
                        //Không làm gì cả
                    }
                    else
                    {
                        MessageBox.Show("Bạn chưa chọn nhà cung cấp mặt hàng");
                        cmbDoiTuong.Focus();
                    }
                }

                if (DgrHangHoa["Ma", DgrHangHoa.SelectedRows[0].Index].Value.ToString() == "")
                {
                    MessageBox.Show("Hàng bạn chọn không có mã");
                    return;
                }

                string maNCC = "";
                if (DanhMucStore.Instance.CurrentStore().Ten.ToUpper().Contains("IBOOK"))
                    maNCC = "IBOOK";
                else if (DanhMucStore.Instance.CurrentStore().Ten.ToUpper().Contains("PHSPHUTHO"))
                    maNCC = "";
                else
                    maNCC = DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)cmbDoiTuong.EditValue).Ma;

                if (RdoTheoPhieuNhap.Checked)
                {
                    foreach (DataGridViewRow r in DgrHangHoa.SelectedRows)
                    {
                        DgrInHang.Rows.Add(DgrHangHoa["Ma", r.Index].Value, DgrHangHoa["Ten", r.Index].Value, DgrHangHoa["GiaBia", r.Index].Value, DgrHangHoa["SoLuong", r.Index].Value,
                                            maNCC);
                    }
                }
                else
                {
                    foreach (DataGridViewRow r in DgrHangHoa.SelectedRows)
                    {
                        DgrInHang.Rows.Add(DgrHangHoa["Ma", r.Index].Value, DgrHangHoa["Ten", r.Index].Value, DgrHangHoa["GiaBia", r.Index].Value, (int)numSoLuongIn.EditValue,
                                            maNCC);
                    }
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            ChooseForPrint();
        }

        private Image GenBarCodeImage(string ma, int width, int height)     //Sinh ảnh mã vạch từ chuỗi mã. Dùng thư viện BarcodeLib.
        {
            try
            {
                BarcodeLib.Barcode barcode = new BarcodeLib.Barcode();
                barcode.Alignment = AlignmentPositions.CENTER;
                barcode.IncludeLabel = false;
                Image image = null;

                decimal check = -1;
                try
                {
                    check = Convert.ToDecimal(ma);
                }
                catch (Exception ex)
                { }

                if (ma.Length == 13 && check != -1)
                    image = barcode.Encode(TYPE.EAN13, ma, Color.Black, Color.White, width, height);
                else if (ma.Length == 8 && check != -1)
                    image = barcode.Encode(TYPE.EAN8, ma, Color.Black, Color.White, width, height);
                else
                    image = barcode.Encode(TYPE.CODE128, ma, Color.Black, Color.White, width, height);
                return image;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        private void PrintA4()  //In A4 tự dọc. Hiện đang dùng tại NS Bách Khoa
        {

            try
            {
                if (DgrInHang.RowCount == 0)
                {
                    MessageBox.Show("Bạn chưa chọn mặt hàng để in mã vạch");
                }
                else
                {
                    DsPrintBarCode ds = new DsPrintBarCode();
                    DataRow row = null;
                    int index = 0;

                    for (int r = 0; r < DgrInHang.RowCount - 1; r++)//moi loai tem
                    {
                        int soLuong = Convert.ToInt32(DgrInHang[3, r].Value);
                        string strTen = "";
                        string strMa = (string)(DgrInHang[0, r].Value);
                        if (!chkInTheoTenNganGon.Checked) strTen = (DgrInHang[1, r].Value).ToString();
                        else
                        {
                            try
                            {
                                strTen = DanhMucVatTuHangHoa.GetByMa(strMa).TenNganGon;
                            }
                            catch (Exception ex)
                            {
                                strTen = (DgrInHang[1, r].Value).ToString();
                            }
                        }
                        if (strTen == "") strTen = (DgrInHang[1, r].Value).ToString();

                        if (strTen.Length > 22)
                        {
                            strTen = strTen.Substring(0, 19) + "...";
                        }

                        for (int c = 0; c < soLuong; c++)//moi tem cua mot loai
                        {
                            if (index == 0)
                            {
                                row = ds.DataTable1.NewRow();
                                ds.DataTable1.Rows.Add(row);
                            }
                            index++;

                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            Image image = GenBarCodeImage((string)(DgrInHang[0, r].Value), BARCODE_WIDTH, BARCODE_HEIGHT);
                            if (image != null) image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

                            switch (index)
                            {
                                case 1:
                                    row["Image1"] = ms.ToArray();
                                    row["Ten1"] = strTen;
                                    row["Ma1"] = strMa;
                                    row["Gia1"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai1"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 2:
                                    row["Image2"] = ms.ToArray();
                                    row["Ten2"] = strTen;
                                    row["Ma2"] = strMa;
                                    row["Gia2"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai2"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 3:
                                    row["Image3"] = ms.ToArray();
                                    row["Ten3"] = strTen;
                                    row["Ma3"] = strMa;
                                    row["Gia3"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai3"] = ((DgrInHang[4, r].Value.ToString()));
                                    //index = 0;
                                    break;
                                case 4:
                                    row["Image4"] = ms.ToArray();
                                    row["Ten4"] = strTen;
                                    row["Ma4"] = strMa;
                                    row["Gia4"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai4"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 5:
                                    row["Image5"] = ms.ToArray();
                                    row["Ten5"] = strTen;
                                    row["Ma5"] = strMa;
                                    row["Gia5"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai5"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 6:
                                    row["Image6"] = ms.ToArray();
                                    row["Ten6"] = strTen;
                                    row["Ma6"] = strMa;
                                    row["Gia6"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai6"] = ((DgrInHang[4, r].Value.ToString()));
                                    index = 0;
                                    break;
                            }
                        }
                    }

                    RptA4Barcode report = new RptA4Barcode();
                    report.SetDataSource(ds);

                    FrmShowReport frm = new FrmShowReport();
                    frm.crystalReportViewer1.ReportSource = report;
                    frm.Show();
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
        private void PrintA5()
        {
            try
            {
                if (DgrInHang.RowCount == 0)
                {
                    MessageBox.Show("Bạn chưa chọn mặt hàng để in mã vạch");
                }
                else
                {
                    DsPrintBarCode ds = new DsPrintBarCode();
                    DataRow row = null;
                    int index = 0;

                    for (int r = 0; r < DgrInHang.RowCount - 1; r++)//moi loai tem
                    {
                        int soLuong = Convert.ToInt32(DgrInHang[3, r].Value);
                        string strTen = "";
                        string strMa = (string)(DgrInHang[0, r].Value);
                        if (!chkInTheoTenNganGon.Checked) strTen = (DgrInHang[1, r].Value).ToString();
                        else
                        {
                            try
                            {
                                strTen = DanhMucVatTuHangHoa.GetByMa(strMa).TenNganGon;
                            }
                            catch (Exception ex)
                            {
                                strTen = (DgrInHang[1, r].Value).ToString();
                            }
                        }
                        if (strTen == "") strTen = (DgrInHang[1, r].Value).ToString();

                        if (strTen.Length > 22)
                        {
                            strTen = strTen.Substring(0, 19) + "...";
                        }

                        for (int c = 0; c < soLuong; c++)//moi tem cua mot loai
                        {
                            if (index == 0)
                            {
                                row = ds.DataTable1.NewRow();
                                ds.DataTable1.Rows.Add(row);
                            }
                            index++;

                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            Image image = GenBarCodeImage((string)(DgrInHang[0, r].Value), BARCODE_WIDTH, BARCODE_HEIGHT);
                            if (image != null) image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

                            switch (index)
                            {
                                case 1:
                                    row["Image1"] = ms.ToArray();
                                    row["Ten1"] = strTen;
                                    row["Ma1"] = strMa;
                                    row["Gia1"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai1"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 2:
                                    row["Image2"] = ms.ToArray();
                                    row["Ten2"] = strTen;
                                    row["Ma2"] = strMa;
                                    row["Gia2"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai2"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 3:
                                    row["Image3"] = ms.ToArray();
                                    row["Ten3"] = strTen;
                                    row["Ma3"] = strMa;
                                    row["Gia3"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai3"] = ((DgrInHang[4, r].Value.ToString()));
                                    index = 0;
                                    break;
                                case 4:
                                    row["Image4"] = ms.ToArray();
                                    row["Ten4"] = strTen;
                                    row["Ma4"] = strMa;
                                    row["Gia4"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai4"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 5:
                                    row["Image5"] = ms.ToArray();
                                    row["Ten5"] = strTen;
                                    row["Ma5"] = strMa;
                                    row["Gia5"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai5"] = ((DgrInHang[4, r].Value.ToString()));
                                    index = 0;
                                    break;
                            }
                        }
                    }

                    RptA5BarCode report2 = new RptA5BarCode();
                    report2.SetDataSource(ds);

                    FrmShowReport frm = new FrmShowReport();
                    frm.crystalReportViewer1.ReportSource = report2;
                    frm.Show();
                }
            }
            catch (SqlException sqlEx)
            {
                throw new CustomException(CustomException.GetSqlExceptionMessage(sqlEx));
            }
            catch (Exception ex)
            {
                if (ex is CustomException) throw ex;
                else
                {
                    throw new Exception(ex.Message);
                }
            }

        }   //Mẫu in A5 cho Techsimex. Mẫu này mua ở Metro
        private void Print3Cot()
        {
            try
            {
                Store store = DanhMucStore.Instance.GetByStoreID(Config.StoreID);

                if (DgrInHang.RowCount == 0)
                {
                    MessageBox.Show("Bạn chưa chọn mặt hàng để in mã vạch");
                }
                else
                {
                    DsPrintBarCode ds = new DsPrintBarCode();
                    DataRow row = null;
                    int index = 0;

                    for (int r = 0; r < DgrInHang.RowCount - 1; r++)//moi loai tem
                    {
                        int soLuong = Convert.ToInt32(DgrInHang[3, r].Value);
                        string strTen = "";
                        string strMa = (string)(DgrInHang[0, r].Value);
                        if (!chkInTheoTenNganGon.Checked) strTen = (DgrInHang[1, r].Value).ToString();
                        else
                        {
                            try
                            {
                                strTen = DanhMucVatTuHangHoa.GetByMa(strMa).TenNganGon;
                            }
                            catch (Exception ex)
                            {
                                strTen = (DgrInHang[1, r].Value).ToString();
                            }
                        }
                        if (strTen == "") strTen = (DgrInHang[1, r].Value).ToString();

                        if (store.Ten.ToUpper().Contains("IBOOK"))
                        {
                            if (strTen.Length > 33)
                                strTen = strTen.Substring(0, 30) + "...";
                        }
                        else
                        {
                            if (strTen.Length > 22)
                                strTen = strTen.Substring(0, 19) + "...";
                        }

                        for (int c = 0; c < soLuong; c++)//moi tem cua mot loai
                        {
                            if (index == 0)
                            {
                                row = ds.DataTable1.NewRow();
                                ds.DataTable1.Rows.Add(row);
                            }
                            index++;

                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            Image image = GenBarCodeImage((string)(DgrInHang[0, r].Value), BARCODE_WIDTH, BARCODE_HEIGHT);
                            if (image != null) image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

                            switch (index)
                            {
                                case 1:
                                    row["Image1"] = ms.ToArray();
                                    row["Ten1"] = strTen;
                                    row["Ma1"] = strMa;
                                    row["Gia1"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai1"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 2:
                                    row["Image2"] = ms.ToArray();
                                    row["Ten2"] = strTen;
                                    row["Ma2"] = strMa;
                                    row["Gia2"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai2"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 3:
                                    row["Image3"] = ms.ToArray();
                                    row["Ten3"] = strTen;
                                    row["Ma3"] = strMa;
                                    row["Gia3"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai3"] = ((DgrInHang[4, r].Value.ToString()));
                                    index = 0;
                                    break;
                            }
                        }
                    }

                    CrystalDecisions.CrystalReports.Engine.ReportClass report = null;

                    string tenDoanhNghiepVietHoa = Config.TenDoanhNghiep.ToUpper();
                    if (tenDoanhNghiepVietHoa.Contains("NINH BÌNH"))
                        report = new RptBarcodeNinhBinh_2013();
                    else if (store.Ten.ToUpper().Contains("BACHKHOA") || store.Ten.ToUpper().Contains("HUYHOANGNH"))
                        report = new RptBarcodeHuyHoangNgocHa();
                    else if (store.Ten.ToUpper().Contains("IBOOK"))
                        report = new RptBarcodeIBOOK();
                    else if (store.Ten.ToUpper().Contains("HUYHOANGSG"))
                        report = new RptBarcodeHuyHoangSaiGonDatamax();
                    else if (store.Ten.ToUpper().Contains("THANHVINH1"))
                        report = new RptBarcodeThanhVinh1();
                    else if (store.Ten.ToUpper().Contains("PHSPHUTHO"))
                        report = new RptBarcodePHSPhuTho();
                    else
                        report = new RptBarcodePHSPhuTho();

                    string oldDefaultPrinter = RegistryPrinter.GetDefaultPrinter().Name;

                    string printerName = "BIXOLON SLP-T400";
                    SetDefaultPrinter(printerName);

                    report.SetDataSource(ds);
                    FrmShowReport frm = new FrmShowReport(oldDefaultPrinter);
                    frm.crystalReportViewer1.ReportSource = report;
                    frm.Show();
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }   //In 3 cột chuẩn theo mãu máy in mã vạch chuyên dụng. Ninh Bình đang sử dụng

        private void Print4Cot()
        {
            try
            {
                Store store = DanhMucStore.Instance.GetByStoreID(Config.StoreID);

                if (DgrInHang.RowCount == 0)
                {
                    MessageBox.Show("Bạn chưa chọn mặt hàng để in mã vạch");
                }
                else
                {
                    DsPrintBarCode ds = new DsPrintBarCode();
                    DataRow row = null;
                    int index = 0;

                    for (int r = 0; r < DgrInHang.RowCount - 1; r++)//moi loai tem
                    {
                        int soLuong = Convert.ToInt32(DgrInHang[3, r].Value);
                        string strTen = "";
                        string strMa = (string)(DgrInHang[0, r].Value);
                        if (!chkInTheoTenNganGon.Checked) strTen = (DgrInHang[1, r].Value).ToString();
                        else
                        {
                            try
                            {
                                strTen = DanhMucVatTuHangHoa.GetByMa(strMa).TenNganGon;
                            }
                            catch (Exception ex)
                            {
                                strTen = (DgrInHang[1, r].Value).ToString();
                            }
                        }
                        if (strTen == "") strTen = (DgrInHang[1, r].Value).ToString();

                        if (store.Ten.ToUpper().Contains("IBOOK"))
                        {
                            if (strTen.Length > 33)
                                strTen = strTen.Substring(0, 30) + "...";
                        }
                        else
                        {
                            if (strTen.Length > 22)
                                strTen = strTen.Substring(0, 19) + "...";
                        }

                        for (int c = 0; c < soLuong; c++)//moi tem cua mot loai
                        {
                            if (index == 0)
                            {
                                row = ds.DataTable1.NewRow();
                                ds.DataTable1.Rows.Add(row);
                            }
                            index++;

                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            Image image = GenBarCodeImage((string)(DgrInHang[0, r].Value), BARCODE_WIDTH, BARCODE_HEIGHT);
                            if (image != null) image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

                            switch (index)
                            {
                                case 1:
                                    row["Image1"] = ms.ToArray();
                                    row["Ten1"] = strTen;
                                    row["Ma1"] = strMa;
                                    row["Gia1"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai1"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 2:
                                    row["Image2"] = ms.ToArray();
                                    row["Ten2"] = strTen;
                                    row["Ma2"] = strMa;
                                    row["Gia2"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai2"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 3:
                                    row["Image3"] = ms.ToArray();
                                    row["Ten3"] = strTen;
                                    row["Ma3"] = strMa;
                                    row["Gia3"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai3"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 4:
                                    row["Image4"] = ms.ToArray();
                                    row["Ten4"] = strTen;
                                    row["Ma4"] = strMa;
                                    row["Gia4"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai4"] = ((DgrInHang[4, r].Value.ToString()));
                                    index = 0;
                                    break;
                            }
                        }
                    }

                    CrystalDecisions.CrystalReports.Engine.ReportClass report = null;
                    if (store.Ten.ToUpper().Contains("CPIN"))
                        report = new RptBarcode_ChuyenDung4Cot();
                    if (store.Ten.ToUpper().Contains("THENAME"))
                        report = new RptBarcode_ChuyenDung4CotTheName1();


                    report.SetDataSource(ds);

                    FrmShowReport frm = new FrmShowReport();
                    frm.crystalReportViewer1.ReportSource = report;
                    frm.Show();
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }   //In 3 cột chuẩn theo mãu máy in mã vạch chuyên dụng. Ninh Bình đang sử dụng
        private void PrintA4ChiCanMaVachVaGia() //Phương thêm cho HuyHoang. Họ chỉ cần mã vạch và giá tiền, to một chút để đè được những mã vạch có sẵn
        {
            try
            {
                if (DgrInHang.RowCount == 0)
                {
                    MessageBox.Show("Bạn chưa chọn mặt hàng để in mã vạch");
                }
                else
                {
                    DsPrintBarCode ds = new DsPrintBarCode();
                    DataRow row = null;

                    int index = 0;

                    for (int r = 0; r < DgrInHang.RowCount - 1; r++)//moi loai tem
                    {
                        int soLuong = Convert.ToInt32(DgrInHang[3, r].Value);
                        for (int c = 0; c < soLuong; c++)//moi tem cua mot loai
                        {
                            if (index == 0)
                            {
                                row = ds.DataTable1.NewRow();
                                ds.DataTable1.Rows.Add(row);
                            }
                            index++;

                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            //Image image = GenBarCodeImage((string)(DgrInHang[0, r].Value), BARCODE_WIDTH, BARCODE_HEIGHT);
                            Image image = GenBarCodeImage((string)(DgrInHang[0, r].Value), 120, 50); //Tỷ lệ mới để in mã vạch lớn hơn cho Huy Hoàng

                            if (image != null) image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

                            switch (index)
                            {
                                case 1:
                                    row["Image1"] = ms.ToArray();
                                    row["Ma1"] = (string)(DgrInHang[0, r].Value);
                                    row["Gia1"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " VNĐ";
                                    break;
                                case 2:
                                    row["Image2"] = ms.ToArray();
                                    row["Ma2"] = (string)(DgrInHang[0, r].Value);
                                    row["Gia2"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " VNĐ";
                                    break;
                                case 3:
                                    row["Image3"] = ms.ToArray();
                                    row["Ma3"] = (string)(DgrInHang[0, r].Value);
                                    row["Gia3"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " VNĐ";
                                    break;
                                case 4:
                                    row["Image4"] = ms.ToArray();
                                    row["Ma4"] = (string)(DgrInHang[0, r].Value);
                                    row["Gia4"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " VNĐ";
                                    break;
                                case 5:
                                    row["Image5"] = ms.ToArray();
                                    row["Ma5"] = (string)(DgrInHang[0, r].Value);
                                    row["Gia5"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " VNĐ";
                                    index = 0;
                                    break;
                            }
                        }
                    }

                    RptBarcodeHuyHoang report = new RptBarcodeHuyHoang();
                    report.SetDataSource(ds);

                    FrmShowReport frm = new FrmShowReport();
                    frm.crystalReportViewer1.ReportSource = report;
                    frm.Show();
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
        private void PrintA4CPIN()  //Dùng cho nhà sách giáo dục Cổ phần In. CPIN
        {
            try
            {
                if (DgrInHang.RowCount == 0)
                {
                    MessageBox.Show("Bạn chưa chọn mặt hàng để in mã vạch");
                }
                else
                {
                    DsPrintBarCode ds = new DsPrintBarCode();
                    DataRow row = null;
                    int index = 0;

                    for (int r = 0; r < DgrInHang.RowCount - 1; r++)//moi loai tem
                    {
                        int soLuong = Convert.ToInt32(DgrInHang[3, r].Value);
                        string strTen = "";
                        string strMa = (string)(DgrInHang[0, r].Value);
                        if (!chkInTheoTenNganGon.Checked) strTen = (DgrInHang[1, r].Value).ToString();
                        else
                        {
                            try
                            {
                                strTen = DanhMucVatTuHangHoa.GetByMa(strMa).TenNganGon;
                            }
                            catch (Exception ex)
                            {
                                strTen = (DgrInHang[1, r].Value).ToString();
                            }
                        }
                        if (strTen == "") strTen = (DgrInHang[1, r].Value).ToString();

                        if (strTen.Length > 22)
                        {
                            strTen = strTen.Substring(0, 19) + "...";
                        }

                        for (int c = 0; c < soLuong; c++)//moi tem cua mot loai
                        {
                            if (index == 0)
                            {
                                row = ds.DataTable1.NewRow();
                                ds.DataTable1.Rows.Add(row);
                            }
                            index++;

                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            Image image = GenBarCodeImage((string)(DgrInHang[0, r].Value), BARCODE_WIDTH, BARCODE_HEIGHT);
                            if (image != null) image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

                            switch (index)
                            {
                                case 1:
                                    row["Image1"] = ms.ToArray();
                                    row["Ten1"] = strTen;
                                    row["Ma1"] = strMa;
                                    row["Gia1"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai1"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 2:
                                    row["Image2"] = ms.ToArray();
                                    row["Ten2"] = strTen;
                                    row["Ma2"] = strMa;
                                    row["Gia2"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai2"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 3:
                                    row["Image3"] = ms.ToArray();
                                    row["Ten3"] = strTen;
                                    row["Ma3"] = strMa;
                                    row["Gia3"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai3"] = ((DgrInHang[4, r].Value.ToString()));
                                    //index = 0;
                                    break;
                                case 4:
                                    row["Image4"] = ms.ToArray();
                                    row["Ten4"] = strTen;
                                    row["Ma4"] = strMa;
                                    row["Gia4"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai4"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 5:
                                    row["Image5"] = ms.ToArray();
                                    row["Ten5"] = strTen;
                                    row["Ma5"] = strMa;
                                    row["Gia5"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai5"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 6:
                                    row["Image6"] = ms.ToArray();
                                    row["Ten6"] = strTen;
                                    row["Ma6"] = strMa;
                                    row["Gia6"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai6"] = ((DgrInHang[4, r].Value.ToString()));
                                    index = 0;
                                    break;
                            }
                        }
                    }

                    RptCPIN report = new RptCPIN();
                    report.SetDataSource(ds);

                    FrmShowReport frm = new FrmShowReport();
                    frm.crystalReportViewer1.ReportSource = report;
                    frm.Show();
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
        private void PrintA4So4DinhLe()  //Dùng cho Số 4 Đinh Lễ
        {
            try
            {
                if (DgrInHang.RowCount == 0)
                {
                    MessageBox.Show("Bạn chưa chọn mặt hàng để in mã vạch");
                }
                else
                {
                    DsPrintBarCode ds = new DsPrintBarCode();
                    DataRow row = null;
                    int index = 0;

                    for (int r = 0; r < DgrInHang.RowCount - 1; r++)//moi loai tem
                    {
                        int soLuong = Convert.ToInt32(DgrInHang[3, r].Value);
                        string strTen = "";
                        string strMa = (string)(DgrInHang[0, r].Value);
                        if (!chkInTheoTenNganGon.Checked) strTen = (DgrInHang[1, r].Value).ToString();
                        else
                        {
                            try
                            {
                                strTen = DanhMucVatTuHangHoa.GetByMa(strMa).TenNganGon;
                            }
                            catch (Exception ex)
                            {
                                strTen = (DgrInHang[1, r].Value).ToString();
                            }
                        }
                        if (strTen == "") strTen = (DgrInHang[1, r].Value).ToString();

                        if (strTen.Length > 25)
                        {
                            strTen = strTen.Substring(0, 25) + "...";
                        }

                        for (int c = 0; c < soLuong; c++)//moi tem cua mot loai
                        {
                            if (index == 0)
                            {
                                row = ds.DataTable1.NewRow();
                                ds.DataTable1.Rows.Add(row);
                            }
                            index++;

                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            Image image = GenBarCodeImage((string)(DgrInHang[0, r].Value), BARCODE_WIDTH, BARCODE_HEIGHT);
                            if (image != null) image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

                            switch (index)
                            {
                                case 1:
                                    row["Image1"] = ms.ToArray();
                                    row["Ten1"] = strTen;
                                    row["Ma1"] = strMa;
                                    row["Gia1"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai1"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 2:
                                    row["Image2"] = ms.ToArray();
                                    row["Ten2"] = strTen;
                                    row["Ma2"] = strMa;
                                    row["Gia2"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai2"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 3:
                                    row["Image3"] = ms.ToArray();
                                    row["Ten3"] = strTen;
                                    row["Ma3"] = strMa;
                                    row["Gia3"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai3"] = ((DgrInHang[4, r].Value.ToString()));
                                    //index = 0;
                                    break;
                                case 4:
                                    row["Image4"] = ms.ToArray();
                                    row["Ten4"] = strTen;
                                    row["Ma4"] = strMa;
                                    row["Gia4"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai4"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 5:
                                    row["Image5"] = ms.ToArray();
                                    row["Ten5"] = strTen;
                                    row["Ma5"] = strMa;
                                    row["Gia5"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai5"] = ((DgrInHang[4, r].Value.ToString()));
                                    index = 0;
                                    break;
                            }
                        }
                    }

                    RptSo4DinhLe report = new RptSo4DinhLe();
                    report.SetDataSource(ds);

                    FrmShowReport frm = new FrmShowReport();
                    frm.crystalReportViewer1.ReportSource = report;
                    frm.Show();
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
        private void PrintThreeColumnBarCodeCTSHN(string mayIn)
        {
            try
            {
                if (DgrInHang.RowCount == 0)
                {
                    MessageBox.Show("Bạn chưa chọn mặt hàng để in mã vạch");
                }
                else
                {
                    DsPrintBarCode ds = new DsPrintBarCode();
                    DataRow row = null;

                    int index = 0;

                    for (int r = 0; r < DgrInHang.RowCount - 1; r++)//moi loai tem
                    {
                        int soLuong = Convert.ToInt32(DgrInHang[3, r].Value);
                        string strTen = (DgrInHang[1, r].Value).ToString();
                        if (strTen.Length > 22)
                        {
                            strTen = strTen.Substring(0, 19) + "...";
                        }

                        for (int c = 0; c < soLuong; c++)//moi tem cua mot loai
                        {
                            if (index == 0)
                            {
                                row = ds.DataTable1.NewRow();
                                ds.DataTable1.Rows.Add(row);
                            }
                            index++;

                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            Image image = GenBarCodeImage((string)(DgrInHang[0, r].Value), BARCODE_WIDTH, BARCODE_HEIGHT);
                            if (image != null) image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

                            if (DanhMucStore.Instance.CurrentStore().Ten.ToUpper().Contains("VIETBOOK"))
                            {
                                switch (index)
                                {
                                    case 1:
                                        row["Image1"] = ms.ToArray();
                                        row["Ten1"] = strTen;
                                        row["Ma1"] = (string)(DgrInHang[0, r].Value);
                                        row["Gia1"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                        try
                                        {
                                            row["ChungLoai1"] = ((DgrInHang[6, r].Value.ToString())); //VietBook thành nhóm hàng, cột số 7, index = 6
                                            row["Text1"] = ((DgrInHang[5, r].Value.ToString()));  //Tên kho cột 6,index = 5
                                        }
                                        catch (Exception)
                                        { }
                                        break;
                                    case 2:
                                        row["Image2"] = ms.ToArray();
                                        row["Ten2"] = strTen;
                                        row["Ma2"] = (string)(DgrInHang[0, r].Value);
                                        row["Gia2"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                        try
                                        {
                                            row["ChungLoai2"] = ((DgrInHang[6, r].Value.ToString()));
                                            row["Text2"] = ((DgrInHang[5, r].Value.ToString()));
                                        }
                                        catch (Exception)
                                        { }
                                        break;
                                    case 3:
                                        row["Image3"] = ms.ToArray();
                                        row["Ten3"] = strTen;
                                        row["Ma3"] = (string)(DgrInHang[0, r].Value);
                                        row["Gia3"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                        try
                                        {
                                            row["ChungLoai3"] = ((DgrInHang[6, r].Value.ToString()));
                                            row["Text3"] = ((DgrInHang[5, r].Value.ToString()));
                                        }
                                        catch (Exception)
                                        { }
                                        index = 0;
                                        break;
                                }
                            }
                            else
                            {
                                switch (index)
                                {
                                    case 1:
                                        row["Image1"] = ms.ToArray();
                                        row["Ten1"] = strTen;
                                        row["Ma1"] = (string)(DgrInHang[0, r].Value);
                                        row["Gia1"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                        row["ChungLoai1"] = ((DgrInHang[4, r].Value.ToString()));
                                        break;
                                    case 2:
                                        row["Image2"] = ms.ToArray();
                                        row["Ten2"] = strTen;
                                        row["Ma2"] = (string)(DgrInHang[0, r].Value);
                                        row["Gia2"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                        row["ChungLoai2"] = ((DgrInHang[4, r].Value.ToString()));
                                        break;
                                    case 3:
                                        row["Image3"] = ms.ToArray();
                                        row["Ten3"] = strTen;
                                        row["Ma3"] = (string)(DgrInHang[0, r].Value);
                                        row["Gia3"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                        row["ChungLoai3"] = ((DgrInHang[4, r].Value.ToString()));
                                        index = 0;
                                        break;
                                }
                            }
                        }
                    }

                    CrystalDecisions.CrystalReports.Engine.ReportClass report = null;
                    report = new RptBarcodeCTSHN();
                    if (mayIn == "GODEX")
                        report = new RptBarcodeVietBookGodex();
                    else //Mặc định là SATO
                        report = new RptBarcodeCTSHN();

                    report.SetDataSource(ds);

                    FrmShowReport frm = new FrmShowReport();
                    frm.crystalReportViewer1.ReportSource = report;
                    frm.Show();
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }

        } //in chuyên dụng, Cty sách HN sử dụng
        private void PrintA4(int soCot)  //In A4 dọc sẵn.
        {

            try
            {
                if (DgrInHang.RowCount == 0)
                {
                    MessageBox.Show("Bạn chưa chọn mặt hàng để in mã vạch");
                }
                else
                {
                    DsPrintBarCode ds = new DsPrintBarCode();
                    DataRow row = null;
                    int index = 0;

                    for (int r = 0; r < DgrInHang.RowCount - 1; r++)//moi loai tem
                    {
                        int soLuong = Convert.ToInt32(DgrInHang[3, r].Value);
                        string strTen = "";
                        string strMa = (string)(DgrInHang[0, r].Value);

                        VatTuHangHoa vthh = DanhMucVatTuHangHoa.GetByMa(strMa);
                        if (!chkInTheoTenNganGon.Checked) strTen = (DgrInHang[1, r].Value).ToString();
                        else
                        {
                            try
                            {
                                strTen = DanhMucVatTuHangHoa.GetByMa(strMa).TenNganGon;
                            }
                            catch (Exception ex)
                            {
                                strTen = (DgrInHang[1, r].Value).ToString();
                            }
                        }
                        if (strTen == "") strTen = (DgrInHang[1, r].Value).ToString();

                        if (soCot == 5)
                        {
                            //mẫu Tommy 109 - cột có thể chứa nhiều chữ kí tự hơn
                            if (strTen.Length > 32)
                                strTen = strTen.Substring(0, 29) + "...";
                        }
                        else
                        {
                            if (strTen.Length > 30)
                                strTen = strTen.Substring(0, 27) + "...";
                        }

                        for (int c = 0; c < soLuong; c++)//moi tem cua mot loai
                        {
                            if (index == 0)
                            {
                                row = ds.DataTable1.NewRow();
                                ds.DataTable1.Rows.Add(row);
                            }
                            index++;

                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            Image image = GenBarCodeImage((string)(DgrInHang[0, r].Value), BARCODE_WIDTH, BARCODE_HEIGHT);
                            if (image != null) image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

                            switch (index)
                            {
                                case 1:
                                    row["Image1"] = ms.ToArray();
                                    row["Ten1"] = strTen;
                                    row["Ma1"] = strMa;
                                    row["Gia1"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai1"] = ((DgrInHang[4, r].Value.ToString()));
                                    if (soCot == index) index = 0;
                                    break;
                                case 2:
                                    row["Image2"] = ms.ToArray();
                                    row["Ten2"] = strTen;
                                    row["Ma2"] = strMa;
                                    row["Gia2"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai2"] = ((DgrInHang[4, r].Value.ToString()));
                                    if (soCot == index) index = 0;
                                    break;
                                case 3:
                                    row["Image3"] = ms.ToArray();
                                    row["Ten3"] = strTen;
                                    row["Ma3"] = strMa;
                                    row["Gia3"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai3"] = ((DgrInHang[4, r].Value.ToString()));
                                    if (soCot == index) index = 0;
                                    break;
                                case 4:
                                    row["Image4"] = ms.ToArray();
                                    row["Ten4"] = strTen;
                                    row["Ma4"] = strMa;
                                    row["Gia4"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai4"] = ((DgrInHang[4, r].Value.ToString()));
                                    if (soCot == index) index = 0;
                                    break;
                                case 5:
                                    row["Image5"] = ms.ToArray();
                                    row["Ten5"] = strTen;
                                    row["Ma5"] = strMa;
                                    row["Gia5"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai5"] = ((DgrInHang[4, r].Value.ToString()));
                                    if (soCot == index) index = 0;
                                    break;
                                case 6:
                                    row["Image6"] = ms.ToArray();
                                    row["Ten6"] = strTen;
                                    row["Ma6"] = strMa;
                                    row["Gia6"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai6"] = ((DgrInHang[4, r].Value.ToString()));
                                    if (soCot == index) index = 0;
                                    break;
                                case 7:
                                    row["Image7"] = ms.ToArray();
                                    row["Ten7"] = strTen;
                                    row["Ma7"] = strMa;
                                    row["Gia7"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai7"] = ((DgrInHang[4, r].Value.ToString()));
                                    if (soCot == index) index = 0;
                                    break;
                                case 8:
                                    row["Image8"] = ms.ToArray();
                                    row["Ten8"] = strTen;
                                    row["Ma8"] = strMa;
                                    row["Gia8"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai8"] = ((DgrInHang[4, r].Value.ToString()));
                                    if (soCot == index) index = 0;
                                    break;
                                case 9:
                                    row["Image9"] = ms.ToArray();
                                    row["Ten9"] = strTen;
                                    row["Ma9"] = strMa;
                                    row["Gia9"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai9"] = ((DgrInHang[4, r].Value.ToString()));
                                    if (soCot == index) index = 0;
                                    break;
                                case 10:
                                    row["Image10"] = ms.ToArray();
                                    row["Ten10"] = strTen;
                                    row["Ma10"] = strMa;
                                    row["Gia10"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai10"] = ((DgrInHang[4, r].Value.ToString()));
                                    if (soCot == index) index = 0;
                                    break;
                                case 11:
                                    row["Image11"] = ms.ToArray();
                                    row["Ten11"] = strTen;
                                    row["Ma11"] = strMa;
                                    row["Gia11"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai11"] = ((DgrInHang[4, r].Value.ToString()));
                                    if (soCot == index) index = 0;
                                    break;
                                case 12:
                                    row["Image12"] = ms.ToArray();
                                    row["Ten12"] = strTen;
                                    row["Ma12"] = strMa;
                                    row["Gia12"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai12"] = ((DgrInHang[4, r].Value.ToString()));
                                    if (soCot == index) index = 0;
                                    break;
                            }
                        }
                    }
                    //Store store = DanhMucStore.Instance.GetByStoreID(Config.StoreID);

                    CrystalDecisions.CrystalReports.Engine.ReportClass report = null;
                    if (soCot == 6)
                        report = new RptBarcodeA4_6cot();
                    else if (soCot == 5)  //Mẫu TOmmy 109 5 hàng 11 cột
                        report = new RptBarcodeA4_5cot_Tommy109();

                    report.SetDataSource(ds);

                    FrmShowReport frm = new FrmShowReport();
                    frm.crystalReportViewer1.ReportSource = report;
                    frm.Show();
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        // in chuyên dụng
        private void btnInChuyenDung_Click(object sender, EventArgs e)
        {
            if (Config.StoreID is int && Config.StoreID > 0)
            {
                Store store = DanhMucStore.Instance.GetByStoreID(Config.StoreID);
                if (store.Ten.ToUpper().Contains("VIETBOOK"))
                    contextMenuChonMayInVietBook.Show(btnInChuyenDung, new Point(0, 0));
                else if (store.Ten.ToUpper().Contains("CPIN") || store.Ten.ToUpper().Contains("THENAME"))
                    Print4Cot();
                else
                    Print3Cot();
            }
            else
            {
                Print3Cot();
            }
        }

        private void inMáyInSATOToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintThreeColumnBarCodeCTSHN("SATO");
        }
        private void inMáyInGODEXToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintThreeColumnBarCodeCTSHN("GODEX");
        }

        // in A4
        private void btnPrintA4_Click(object sender, EventArgs e)
        {
            try
            {
                string tenDoanhNghiepVietHoa = Config.TenDoanhNghiep.ToUpper();
                string storeName = DanhMucStore.Instance.GetByStoreID((int)Config.StoreID).Ten.ToUpper();
                if (tenDoanhNghiepVietHoa.Contains("TECHSIMEX")) PrintA5();
                //else if (storeName.Contains("HUYHOANG") || tenDoanhNghiepVietHoa.Contains("HUYHOANG")) PrintA4ChiCanMaVachVaGia();
                else if (storeName.Contains("HATHANH")) PrintA4CPIN();
                else if (storeName.Contains("TTSHN")) PrintA4So4DinhLe();
                else if (storeName.Contains("MINH"))
                {
                    contextMenuStripChonMayInMinh.Show(btnPrintA4, new Point(0, 0));
                }
                else if (storeName.Contains("CPIN")) PrintA4(6);
                else PrintA4();
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbNhomHang_EditValueChanged(object sender, EventArgs e)
        {
            FrmProgressBar.StartShowProgress();
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                txtFindMa.Text = "";
                TxtFindName.Text = "";
                RdoTheoPhieuNhap.Checked = false;
                RdoToanBoKhoHang.Checked = true;

                cmd.CommandText = string.Format("SELECT * FROM VatTuHangHoa WHERE NhomVatTuHangHoaID = '{0}'", cmbNhomHang.EditValue.ToString());

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                DgrHangHoa.DataSource = ds.Tables[0].DefaultView;
                DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bán lẻ";
                DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                DgrHangHoa.Columns["GiaBia"].Width = 80;
                DgrHangHoa.Columns["Ten"].Width = 200;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
            }
            FrmProgressBar.FinishShowProgress();
        }

        private void toolStripMenuItemMau5CotTommy109_Click(object sender, EventArgs e)
        {
            PrintA4(5);
        }

        private void toolStripMenuItemMau6Cot_Click(object sender, EventArgs e)
        {
            PrintA4(6);
        }

        private void CbDonVi_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void DgrHangHoa_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

    }

    public class RegistryPrinter
    {
        /// <summary>
        /// Creates a new instance of a <see cref="RegistryPrinter"/>.
        /// </summary>
        /// <param name="name">The name of the printer.</param>
        /// <param name="value">The registry value of the printer.</param>
        internal RegistryPrinter(string name, string value)
        {
            this.name = name;
            this.value = value;
        }

        public static RegistryPrinter[] InstalledPrinters
        {
            get
            {
                string subkey = @"Software\Microsoft\Windows NT\CurrentVersion\PrinterPorts";
                RegistryKey key = Registry.CurrentUser.OpenSubKey(subkey, false);
                string[] printerNames = key.GetValueNames();
                RegistryPrinter[] printers = new RegistryPrinter[printerNames.Length];
                for (int i = 0; i < printerNames.Length; i++)
                    printers[i] = new RegistryPrinter(printerNames[i], (string)key.GetValue(printerNames[i]));
                key.Close();
                return printers;
            }
        }

        /// <summary>
        /// Gets the name of the printer.
        /// </summary>
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                string subkey = @"Software\Microsoft\Windows NT\CurrentVersion\PrinterPorts";
                RegistryKey key = Registry.CurrentUser.OpenSubKey(subkey, false);
                key.SetValue(value, Value);
                key.DeleteValue(name);
                name = value;
                key.Close();
            }
        }

        /// <summary>
        /// Gets the registry value of the printer.
        /// </summary>
        public string Value
        {
            get
            {
                return value;
            }
        }

        /// <summary>
        /// Set this printer as the default printer for the <see cref="Registry.CurrentUser"/>.
        /// </summary>
        public void SetAsDefaultPrinter()
        {
            Hashtable printers = new Hashtable();
            string subkey = @"Software\Microsoft\Windows NT\CurrentVersion\Windows";
            RegistryKey key = Registry.CurrentUser.OpenSubKey(subkey, true);
            string[] subvalues = value.Split(',');
            key.SetValue("Device", name + "," + subvalues[0] + "," + subvalues[1]);
            key.Close();
        }

        public static RegistryPrinter GetDefaultPrinter()
        {
            string subkey = @"Software\Microsoft\Windows NT\CurrentVersion\Windows";
            RegistryKey key = Registry.CurrentUser.OpenSubKey(subkey, false);
            string defaultPrinter = ((string)key.GetValue("Device")).Split(',')[0];
            key.Close();
            foreach (RegistryPrinter printer in InstalledPrinters)
                if (printer.Name == defaultPrinter)
                    return printer;
            return null;
        }

        private string name;
        private string value;
    }
}

